package com.stone.im.geteway.websocket;

import com.stone.im.geteway.tcp.SessionManager;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("完成连接"+(SocketChannel)ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel channel = (SocketChannel)ctx.channel();
        SessionManager instance = SessionManager.getInstance();
        instance.removeClient(channel);
        System.out.println("检测到断开连接，删除连接"+channel.remoteAddress().toString());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        Channel channel = ctx.channel();//对socketchannel进行缓存，客户推送消息，直接去缓存里找socketchannel
        SessionManager instance = SessionManager.getInstance();
        String message = msg.text();
        if (message.startsWith("发起用户认证")) {
            String token = message.split("\\|")[2];

            String userId = message.split("\\|")[1];

            instance.addClient(userId, (SocketChannel) channel);
            System.out.println("对用户发起的认证确认完毕，缓存客户长连接"+ctx.channel().remoteAddress().toString());
        }else {
            String userId = message.split("\\|")[1];
            if (!instance.existClient(userId)) {
                ctx.channel().writeAndFlush("用户未登录");
            }
        }
    }
}
